import axios from 'axios'
import qs from 'qs'
import {
  MessageBox,
  Message
} from 'element-ui'
import store from '@/store'
import {
  getToken
} from '@/utils/auth'
import Cookies from 'js-cookie'

import {
  vueBus
} from "@/plugins/index"

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
  headers: {
    "content-type": "application/json; charset=UTF-8"
  }

})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // console.log(config);
    // console.log(store.getters.token);
    // const authToken = getToken();
    // console.log(authToken);
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['x-authorization'] = store.getters.token;
    }

    // // 拿到csrf的cookie token
    // const csrfToken = Cookies.get('eggCsrfCookieName');
    // console.log(csrfToken);
    // // egg携带csrf token
    // if (csrfToken) {
    //   config.headers['ding-admin-x-csrf-token'] = csrfToken;
    // }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    const {
      config
    } = response
    // console.log(response);


    /* 先检查http的状态码 */
    if (response.status === 200 && res.code !== undefined) {
      /* 再判断自定义code */
      if (res.code === 20000) {
        return Promise.resolve(res.data);
      }

      /* 50000通用错误code */
      if (res.is_error && res.code === 50000) {
        /* 请求axios的config可携带此参数，用于默认是否触发错误提示。传递true进来则自行处理错误信息提示。 */
        if (!config.isCustomMsg) {
          Message({
            type: "error",
            message: res.msg
          })
        }
        return Promise.reject(res);
      }

      console.log(res);
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {

        // to re-login
        MessageBox.confirm('您的会话已失效，请重新登录。', '提醒', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 发出事件，在app.vue中监听，重新登录 的事件。
          vueBus.$emit("re-login-by-not-token")
        }).catch(err => {})
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      /* 请求成功，但http状态码不是200或没有带自定义code */
      // console.log("res status not 200---->",response);
      return Promise.resolve(res)
    }
  },
  error => {
    /* 请求失败，比如500,404等服务器提示的错误。 */
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
